package com.sbs.demo.common;

import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.net.SocketException;
import java.util.Set;

/**
 * Web项目统一异常拦截
 *
 * @author luwenmin
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionTranslator {

    @Resource
    private HttpServletRequest httpServletRequest;

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseData<?> handleError(MissingServletRequestParameterException e) {
        log.warn("Missing Request Parameter", e);
        String message = String.format("Missing Request Parameter: %s", e.getParameterName());
        return ResponseData.fail(ResultCode.INVALID_PARAMETER.getCode(), message);
    }

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public ResponseData<?> handleError(MethodArgumentTypeMismatchException e) {
        log.warn("Method Argument Type Mismatch", e);
        String message = String.format("Method Argument Type Mismatch: %s", e.getName());
        return ResponseData.fail(ResultCode.INVALID_PARAMETER.getCode(), message);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseData<?> handleError(MethodArgumentNotValidException e) {
        log.warn("Method Argument Not Valid", e);
        BindingResult result = e.getBindingResult();
        FieldError error = result.getFieldError();
        String message = String.format("%s", error.getDefaultMessage());
        return ResponseData.fail(ResultCode.INVALID_PARAMETER.getCode(), message);
    }

    @ExceptionHandler(BindException.class)
    public ResponseData<?> handleError(BindException e) {
        FieldError error = e.getFieldError();
        log.warn("Bind Exception field:{}, message:{}", error.getField(), error.getDefaultMessage());
        String message = String.format("%s", error.getDefaultMessage());
        return ResponseData.fail(ResultCode.INVALID_PARAMETER, message);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseData<?> handleError(ConstraintViolationException e) {
        log.warn("Constraint Violation", e);
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        ConstraintViolation<?> violation = violations.iterator().next();
        String path = ((PathImpl) violation.getPropertyPath()).getLeafNode().getName();
        String message = String.format("%s", violation.getMessage());
        return ResponseData.fail(ResultCode.INVALID_PARAMETER, message);
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public ResponseData<?> handleError(NoHandlerFoundException e) {
        log.error("404 Not Found", e);
        return ResponseData.fail(HttpStatus.INTERNAL_SERVER_ERROR, "404 Not Found");
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseData<?> handleError(HttpMessageNotReadableException e) {
        log.error("Message Not Readable", e);
        return ResponseData.fail(HttpStatus.INTERNAL_SERVER_ERROR, "请求参数错误");
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseData<?> handleError(HttpRequestMethodNotSupportedException e) {
        log.error("Request Method Not Supported", e);
        return ResponseData.fail(HttpStatus.METHOD_NOT_ALLOWED, e.getMessage());
    }

    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public ResponseData<?> handleError(HttpMediaTypeNotSupportedException e) {
        log.error("Media Type Not Supported", e);
        return ResponseData.fail(HttpStatus.UNSUPPORTED_MEDIA_TYPE, e.getMessage());
    }

    @ExceptionHandler(ServiceException.class)
    public ResponseData<?> handleError(ServiceException e) {
        log.error("Service Exception:{}", e.getMsg());
        int errorCode = e.getCode();
        errorCode = errorCode == 0 ? CommonConstant.FAIL : errorCode;
        if (e.getCode().equals(ResultCode.SENTINEL_LIMIT.getCode())
                || e.getCode().equals(ResultCode.INTERNAL_SERVER_ERROR.getCode())
                || e.getCode().equals(ResultCode.API_NETWORK_ERROR.getCode())
                || e.getCode().equals(ResultCode.API_TIMEOUT.getCode())
                || e.getCode().equals(ResultCode.API_INVALID_RESPONSE.getCode())
        ) {
            log.info("error code:{}, msg:{}, requestUri:{}",
                    e.getCode(), e.getMsg(), httpServletRequest == null ? "" : httpServletRequest.getRequestURI(), e);
        }
        return ResponseData.fail(errorCode, e.getMsg());
    }

    @ExceptionHandler(SocketException.class)
    public ResponseData<?> handleError(SocketException e) {
        log.error("Socket Exception", e);
        return ResponseData.fail(ResultCode.INTERNAL_SERVER_ERROR.getCode(), ResultCode.INTERNAL_SERVER_ERROR.getMsg());
    }

    @ExceptionHandler(Exception.class)
    public ResponseData<?> handleError(Exception e) {
        log.error("Internal Server Error, requestUri:{}",
                httpServletRequest == null ? "" : httpServletRequest.getRequestURI(), e);
        return ResponseData.fail(ResultCode.INTERNAL_SERVER_ERROR.getCode(), ResultCode.INTERNAL_SERVER_ERROR.getMsg());
    }

}
